<!DOCTYPE html>
<html>
  <head>
    <title>Import Debug Test</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        padding: 20px;
        background: #f5f5f5;
      }
      .test-container {
        max-width: 600px;
        margin: 0 auto;
        background: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      }
      .test-section {
        margin: 20px 0;
        padding: 15px;
        border: 1px solid #ddd;
        border-radius: 4px;
      }
      .test-section h3 {
        margin-top: 0;
        color: #333;
      }
      button {
        padding: 10px 20px;
        margin: 5px;
        border: none;
        border-radius: 4px;
        background: #007cba;
        color: white;
        cursor: pointer;
      }
      button:hover {
        background: #005a87;
      }
      .log {
        background: #f0f0f0;
        padding: 10px;
        margin: 10px 0;
        border-radius: 4px;
        font-family: monospace;
        font-size: 12px;
        max-height: 200px;
        overflow-y: auto;
      }
      .success {
        color: green;
      }
      .error {
        color: red;
      }
      .warning {
        color: orange;
      }
      input[type="file"] {
        margin: 10px 0;
        padding: 5px;
      }
    </style>
  </head>
  <body>
    <div class="test-container">
      <h1>🔍 Import Debug Test</h1>

      <div class="test-section">
        <h3>📄 Single File Import Test</h3>
        <p>Test importing your JSON file one by one to isolate issues:</p>
        <input type="file" id="singleFileInput" accept=".json" />
        <button onclick="testSingleFile()">Test Single File Import</button>
      </div>

      <div class="test-section">
        <h3>📁 Folder Import Test</h3>
        <p>Test folder import with extensive debugging:</p>
        <input type="file" id="folderTestInput" webkitdirectory multiple />
        <button onclick="testFolderImport()">
          Test Folder Import (Debug Mode)
        </button>
      </div>

      <div class="test-section">
        <h3>🧪 JSON Validation Test</h3>
        <p>Test your JSON file format:</p>
        <input type="file" id="jsonTestInput" accept=".json" />
        <button onclick="testJSONFormat()">Validate JSON Format</button>
      </div>

      <div class="test-section">
        <h3>📊 Debug Log</h3>
        <div id="debugLog" class="log"></div>
        <button onclick="clearLog()">Clear Log</button>
      </div>
    </div>

    <script>
      function log(message, type = "info") {
        const logDiv = document.getElementById("debugLog");
        const timestamp = new Date().toLocaleTimeString();
        const logEntry = document.createElement("div");
        logEntry.className = type;
        logEntry.innerHTML = `[${timestamp}] ${message}`;
        logDiv.appendChild(logEntry);
        logDiv.scrollTop = logDiv.scrollHeight;
        console.log(`[${type.toUpperCase()}] ${message}`);
      }

      function clearLog() {
        document.getElementById("debugLog").innerHTML = "";
      }

      async function testSingleFile() {
        const fileInput = document.getElementById("singleFileInput");
        const file = fileInput.files[0];

        if (!file) {
          log("❌ No file selected", "error");
          return;
        }

        log(`🚀 Testing single file: ${file.name}`, "info");
        log(
          `📏 File size: ${file.size} bytes (${(file.size / 1024).toFixed(
            2
          )} KB)`,
          "info"
        );

        try {
          // Test file reading
          log("📖 Reading file...", "info");
          const text = await file.text();
          log(`✅ File read successfully, length: ${text.length}`, "success");

          // Test JSON parsing
          log("🔍 Parsing JSON...", "info");
          const jsonData = JSON.parse(text);
          log("✅ JSON parsing successful", "success");

          // Validate structure
          log("🏗️ Validating structure...", "info");
          if (jsonData.account && jsonData.account.cookies) {
            log(
              `✅ Valid structure found: ${jsonData.account.cookies.length} cookies`,
              "success"
            );
          } else if (Array.isArray(jsonData)) {
            log(
              `✅ Cookie array format: ${jsonData.length} cookies`,
              "success"
            );
          } else {
            log("⚠️ Unknown JSON structure", "warning");
          }

          // Test extension message (if available)
          if (typeof chrome !== "undefined" && chrome.runtime) {
            log("📤 Testing extension message...", "info");
            try {
              const response = await chrome.runtime.sendMessage({
                type: "importAccountJSON",
                jsonText: text,
                customName: null,
              });
              if (response.success) {
                log(`🎉 Import successful: ${response.data}`, "success");
              } else {
                log(`❌ Import failed: ${response.error}`, "error");
              }
            } catch (msgError) {
              log(`❌ Message error: ${msgError.message}`, "error");
            }
          } else {
            log("⚠️ Chrome extension context not available", "warning");
          }
        } catch (error) {
          log(`💥 Error: ${error.message}`, "error");
        }
      }

      async function testFolderImport() {
        const folderInput = document.getElementById("folderTestInput");
        const files = folderInput.files;

        if (!files || files.length === 0) {
          log("❌ No folder selected", "error");
          return;
        }

        log(`🚀 Testing folder import: ${files.length} files`, "info");

        // Filter JSON files
        const jsonFiles = Array.from(files).filter((file) =>
          file.name.toLowerCase().endsWith(".json")
        );

        log(`📁 Found ${jsonFiles.length} JSON files`, "info");

        if (jsonFiles.length === 0) {
          log("❌ No JSON files in folder", "error");
          return;
        }

        // Test each file individually
        for (let i = 0; i < Math.min(jsonFiles.length, 3); i++) {
          // Limit to 3 files for testing
          const file = jsonFiles[i];
          log(`\n📄 Testing file ${i + 1}: ${file.name}`, "info");

          try {
            const text = await file.text();
            const jsonData = JSON.parse(text);
            log(`  ✅ File ${i + 1} OK: ${text.length} bytes`, "success");
          } catch (error) {
            log(`  ❌ File ${i + 1} ERROR: ${error.message}`, "error");
          }
        }

        if (jsonFiles.length > 3) {
          log(`... and ${jsonFiles.length - 3} more files`, "info");
        }
      }

      async function testJSONFormat() {
        const fileInput = document.getElementById("jsonTestInput");
        const file = fileInput.files[0];

        if (!file) {
          log("❌ No file selected", "error");
          return;
        }

        log(`🔍 Validating JSON format: ${file.name}`, "info");

        try {
          const text = await file.text();
          const jsonData = JSON.parse(text);

          log("✅ JSON is valid", "success");
          log(`📋 Structure preview:`, "info");

          if (jsonData.version) {
            log(`  - Version: ${jsonData.version}`, "info");
          }
          if (jsonData.extension) {
            log(`  - Extension: ${jsonData.extension}`, "info");
          }
          if (jsonData.account) {
            log(`  - Account name: ${jsonData.account.name || "N/A"}`, "info");
            log(
              `  - Account email: ${jsonData.account.email || "N/A"}`,
              "info"
            );
            log(
              `  - Account status: ${jsonData.account.status || "empty"}`,
              "info"
            );
            log(
              `  - Cookies count: ${jsonData.account.cookies?.length || 0}`,
              "info"
            );
          }

          // Size check
          const sizeKB = text.length / 1024;
          if (sizeKB > 512) {
            log(
              `⚠️ File is large: ${sizeKB.toFixed(2)} KB (>512KB limit)`,
              "warning"
            );
          } else {
            log(`✅ File size OK: ${sizeKB.toFixed(2)} KB`, "success");
          }
        } catch (error) {
          log(`❌ JSON validation failed: ${error.message}`, "error");
        }
      }

      // Initialize
      log("🔧 Debug tool initialized", "info");
      log("Select a file or folder to test import functionality", "info");
    </script>
  </body>
</html>
